package com.manli.api.util;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.alibaba.druid.sql.SQLUtils;

/**
 * sql校验
 * @author Shensg
 *
 * 2020年5月7日
 */
public class SqlInjectionCheckUtils {
	
	/**
	 * sql注入
	 * @param sql
	 * @param params
	 */
	public static boolean injectionSqlCheck(String sql , String params) {
		boolean paramsInjection = false;
		boolean sqlInjection = false;
		/**
		 * 参数校验
		 */
		/*Pattern pattern= Pattern.compile("\\b(and|exec|insert|select|drop|grant|alter|delete|update|count|chr|mid|master|truncate|char|declare|or)\\b|(\\*|;|--|\\+|'|%)");
	    Matcher matcher=pattern.matcher(params.toLowerCase());
	    paramsInjection = matcher.find();*/
	    /**
	     * sql校验
	     */
	    Pattern patternSql= Pattern.compile("(--)");
	    Matcher matcherSql=patternSql.matcher(sql.toLowerCase());
	    sqlInjection = matcherSql.find();
	    /**
	     * 一条sql只能存在一条可执行语句
	     */
	    List<com.alibaba.druid.sql.ast.SQLStatement> stmtList = SQLUtils.parseStatements(sql, "mysql");
	    if (stmtList.size()>1) {
	    	sqlInjection = true;
		}
	    
	    return (sqlInjection || paramsInjection);
	}
	
	public static void main(String[] args) {
		String sql = "insert into a(id) values(?) select 1 from b";
		List<com.alibaba.druid.sql.ast.SQLStatement> stmtList = SQLUtils.parseStatements(sql, "mysql");
	    //解析出的独立语句的个数
	    System.out.println("size is:" + stmtList.size());
	    System.out.println(injectionSqlCheck("select * from user where a='1' ","*"));
	}
}
